﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sunny.UI;
using System.Speech;

namespace MMS
{
    public partial class Page_CheckOut : UIPage
    {
        public Page_CheckOut()
        {
            InitializeComponent();
        }
        public string storeName { get;  set;}//超市名
        public string opeID { get; set; }//操作员ID
        public string opeName { get; set; }//操作员
        string csmID;//消费者ID
        string bilID;//单据ID
        List<string> gosList = new List<string>();//商品信息,商品 ID 的集合
        int gosNumber;//商品数量
        string bilMoney;//消费金额
        string rule = "暂无优惠(默认)";
        int addGread=0;//每10元积分
        string disCount = "1";//折扣率
        db_mmsEntities conn = new db_mmsEntities();
        private void Page_CheckOut_Load(object sender, EventArgs e)
        {
            this.Focus();
            uiDataGridView1.SetRowHeight(30);
        }

        /// <summary>
        /// 监听键盘事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Page_CheckOut_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F6)
            {
                txt_GoodsNb.Focus();
            }
            else if (e.KeyCode == Keys.F7)//Space空格
            {
                this.btn_Add_Click(sender, e);
            }
            else if (e.KeyCode == Keys.Down)
            {
                //cmb_Select.;
                int index = cmb_Select.Items.IndexOf(cmb_Select.Text);
                index++;
                if (index > cmb_Select.Items.Count-1)
                {
                    index = 0;
                }

                cmb_Select.Text = cmb_Select.Items[index].ToString();

            }
            else if (e.KeyCode == Keys.F9)
            {
                txt_MemberNb.Focus();
            }
            else if (e.KeyCode == Keys.F10)
            {
                txt_GetMoney.Focus();
            }
            else if (e.KeyCode == Keys.F11)
            {
                this.btn_MemberPay_Click(sender, e);
            }
            else if (e.KeyCode == Keys.F12)
            {
                this.btn_CommonPay_Click(sender, e);
            }
            else if (e.KeyCode == Keys.Delete)
            {
                reSet();
            }
            else if (e.KeyCode == Keys.Enter)
            {
                this.select_MemberInfo(sender, e);
            }

        }


        /// <summary>
        /// 追加商品到显示界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        private void btn_Add_Click(object sender, EventArgs e)
        {
            
            string str = txt_GoodsNb.Text;//商品条码
            var temp = conn.tb_goods.Where(r => r.goodsID == str&&r.isShow==1).FirstOrDefault();
            if (temp == null)
            {
                return;
            }
            //查询视图中是否存在次商品
            if(gosList.IndexOf(str)== -1)
            {
                //视图中不存在商品
                //向视图中填充数据
                string[] row = new string[] { temp.goodsID, temp.goodsName, temp.goodsParam, temp.goodsUnits, "1", temp.putPrice, temp.putPrice };
                uiDataGridView1.Rows.Add(row);
                //向列表中添加商品编码
                gosList.Add(str);
            }
            else
            {
                //存在给商品数量加一，价格变动
                for (int i = 0; i < uiDataGridView1.RowCount; i++)
                {
                    if(str== uiDataGridView1.Rows[i].Cells[0].Value.ToString())
                    {
                        //找到商品所在列
                        uiDataGridView1.Rows[i].Cells[4].Value=(Convert.ToInt32(uiDataGridView1.Rows[i].Cells[4].Value.ToString())+1).ToString();
                        uiDataGridView1.Rows[i].Cells[6].Value=(float.Parse(uiDataGridView1.Rows[i].Cells[6].Value.ToString())+float.Parse(temp.putPrice)).ToString();
                    }
                    

                }

            }

            

            countInfo();
            //MessageBox.Show();
            txt_GoodsNb.Clear();
            txt_GoodsNb.Focus();
        }


        
        /// <summary>
        /// 双击删除行商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiDataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int index = e.RowIndex;
            //MessageBox.Show(index.ToString());
            //所在行商品编号
            string number=uiDataGridView1.Rows[index].Cells[0].Value.ToString();
            gosList.Remove(number);
            uiDataGridView1.Rows.RemoveAt(index);
        }

        private void uiTextBox1_TextChanged(object sender, EventArgs e)
        {
            float getmoney=0;
            float sumMoney = 0;
            if (lab_SumMoney.Text!="")
            {
                sumMoney = float.Parse(lab_SumMoney.Text);
            }
            if (txt_GetMoney.Text != "")
            {
                getmoney = float.Parse(txt_GetMoney.Text);
            }
            
            lab_PutMoney.Text = (getmoney - sumMoney).ToString();
        }

        /// <summary>
        /// 清空数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DataClear_Click(object sender, EventArgs e)
        {
            reSet();
        }
        /// <summary>
        /// 会员结账
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_MemberPay_Click(object sender, EventArgs e)
        {
            if (uiDataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("商品为空！");
                return;
            }
            if (lab_MemberNm.Text == "")
            {
                Console.WriteLine("未查询到会员信息！");
                return;
            }
            if (float.Parse(lab_PutMoney.Text) < 0)
            {
                Console.WriteLine("实收金额有误！");
                return;
            }
            setID();
            setData();
            readTxt("尊敬的"+lab_MemberTb.Text+"顾客，您本次共消费"+ lab_SumMoney.Text + "元，本次积分" +Convert.ToInt32(float.Parse(lab_SumMoney.Text))/10 * addGread+"分，累计积分"+lab_MemberAr.Text+"分，欢迎您的光临！谢谢！");
            reSet();
        }
        /// <summary>
        /// 普通结账
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_CommonPay_Click(object sender, EventArgs e)
        {
            if (uiDataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("商品为空！");
                return;
            }
            if (rule!= "暂无优惠(默认)")
            {
                Console.WriteLine("普通用户无法享受优惠！");
                return;
            }
            if (float.Parse(lab_PutMoney.Text) < 0)
            {
                Console.WriteLine("实收金额有误！");
                return;
            }

            setID();
            setData();
            readTxt("普通结账，应收"+lab_SumMoney.Text+"元，实收"+txt_GetMoney.Text+"元，找零"+lab_PutMoney.Text+"元");
            reSet();
        }


        /*自定义函数*/
        private void inIt()
        {

        }


        /// <summary>
        /// 输入会员卡号后查询信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void select_MemberInfo(object sender, EventArgs e)
        {
            string meNb = txt_MemberNb.Text;
            var member_Info = conn.tb_member.Where(r => r.memberID == meNb).FirstOrDefault();
            if (member_Info != null)
            {
                //查询到会员信息
                //Console.WriteLine("查询到");
                string meType;
                lab_MemberNm.Text = member_Info.memberName;
                lab_MemberAr.Text = member_Info.address;
                switch (member_Info.type)
                {
                    case 0://白金卡
                        meType = "白金卡";
                        addGread = 3;
                        break;
                    case 1://金卡
                        meType = "金卡";
                        addGread = 2;
                        break;
                    case 2://银卡
                        meType = "银卡";
                        addGread = 1;
                        break;
                    case 3:
                        meType = "未知类型";
                        break;
                    default:
                        meType = "错误信息";
                        break;
                }
                lab_MemberTb.Text = meType;
                return;
            }
            //Console.WriteLine("未查到");
        }

        /// <summary>
        /// 统计
        /// </summary>
        private void countInfo()
        {
            //计算总数
            float sumMoney = 0;//总金额
            int sum = 0;//总数量
            
            for (int i = 0; i < uiDataGridView1.RowCount; i++)
            {
                
                int d = Convert.ToInt32(uiDataGridView1.Rows[i].Cells[4].Value);
                string f = uiDataGridView1.Rows[i].Cells[6].Value.ToString();
                
                sumMoney += float.Parse(f);
                sum += d;
            }
            //全局变量赋值
            
            gosNumber = sum;
            bilMoney = (sumMoney*float.Parse(disCount)).ToString();

            
            //更新数据
            lab_SumMoney.Text = bilMoney.ToString();
            lab_Sum.Text = gosNumber.ToString();
        }

        /// <summary>
        /// 储存数据到数据库
        /// </summary>
        private void setData()
        {
            //储存消费者信息
            tb_consumer consumer = new tb_consumer();
            consumer.consumerID = csmID;
            consumer.billID = bilID;
            consumer.memberID = txt_MemberNb.Text;
            conn.tb_consumer.Add(consumer);

            //储存消费单据
            tb_bill bill = new tb_bill();
            bill.billsID = bilID;
            bill.goodsInfo = string.Join(",", gosList.ToArray());//拼接字符串;
            bill.consumerID = csmID;
            bill.goodsNumber = gosNumber;
            bill.billsMoney = bilMoney;
            bill.billsTime = DateTime.Now;
            bill.operateName = opeName;
            bill.isShow = 1;
            conn.tb_bill.Add(bill);
            //保存数据到数据库
            conn.SaveChanges();
        }
        private void setID()
        {

            csmID = DateTime.Now.ToString("yyMMddHHmmss");
            bilID = DateTime.Now.ToString("yyMMddHHmmss") + opeID;
        }
        /// <summary>
        /// 优惠规则
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmb_Select_TextChanged(object sender, EventArgs e)
        {
            rule = cmb_Select.Text;

            //Console.WriteLine(rule);
        }

        /// <summary>
        /// 朗读文本
        /// </summary>
        /// <param name="txt"></param>
        private void readTxt(string txt)
        {
            //实例化SpeechSynthesizer类
            var reader = new System.Speech.Synthesis.SpeechSynthesizer();
            //reader.Speak(txt);
            //异步使用字符串内容的语言,播放
            reader.SpeakAsync(txt);
        }
        private void reSet()
        {
            uiDataGridView1.ClearRows();//清除视图所有行
            lab_Sum.Text = "0";//重置商品总数
            lab_SumMoney.Text = "0";//重置商品总金额
            lab_PutMoney.Text = "0";//重置应收金额
            txt_GetMoney.Text = "0";//重置找零
            txt_MemberNb.Text = "";//重置会员卡号
            lab_MemberNm.Text = "";//重置会员名
            lab_MemberAr.Text = "";//重置会员总积分
            lab_MemberTb.Text = "";//重置会员类型
            cmb_Select.Text = "";//重置优惠规则到默认
            rule = "暂无优惠(默认)";//设置默认优惠规则
            gosList.Clear();//清空选中商品ID列表
        }

        private void reckonRule(string rule)
        {
            
            switch (rule)
            {
                case "暂无优惠(默认)":

                    break;
                case "会员积分":

                    break;
                case "会员折扣":

                    break;
                case "全单折扣":

                    break;
                default:
                    break;

            }
        }
    }
}
